import csv
import re
from typing import Any

import requests

import config_util

sn = None


def csv_writerows(header: list, dic: list, file_name: str):
    with open(file_name, 'w', encoding='utf-8', newline='') as file:
        # 1.创建DicetWriter对象
        dic_writer = csv.DictWriter(file, header)
        # 2.写表头
        dic_writer.writeheader()
        # 3.写入数据(一次性写入多行)
        dic_writer.writerows(dic)


def csv_writerow(header: list, dic: dict, file_name: str):
    with open(file_name, 'w', encoding='utf-8', newline='') as file:
        # 1.创建DicetWriter对象
        dic_writer = csv.DictWriter(file, header)
        # 2.写表头
        dic_writer.writeheader()
        # 3.写入数据(一次性写入多行)
        dic_writer.writerow(dic)


def csv_get_data(path: str) -> list:
    lt = []
    with open(path) as file:
        f_csv = csv.reader(file)
        headers = next(f_csv)
        for row in f_csv:
            lt.append(row)
    return lt


def rq(url: str, headers: dict) -> str:
    print("爬取链接：" + url, end="\t响应状态码：")
    r = requests.get(url, headers=headers, allow_redirects=False)
    print(r.status_code)
    return r.text


def re_whitespace(str: str) -> str:
    return str.replace(" ", "").replace("  ", "").replace("\n", "")


def write_file(path: str, content: str):
    with open(path, "w", encoding='utf-8') as file:
        file.write(content)


def login(email: str, password: str):
    global sn
    sn = requests.session()
    data = {
        "email": email,
        "password": password
    }
    # 登录
    url = "https://www.letpub.com.cn/content/index.php?action=login"
    result = sn.post(url, data=data)
    c = re.compile(".*用户名或者密码不正确.*")
    r = re.findall(c, result.text)
    if len(r) > 0:
        return False
    return True


def my_session() -> requests.session:
    conf = config_util.get()
    if sn is None:
        if login(conf['email'], conf['password']) is False:
            return None
    return sn


def sn_get(win, url: str) -> str:
    print("爬取链接：" + url, end="\t响应状态码：")
    win.show_log("正在爬取链接：" + url)
    re = my_session().get(url)
    print(re.status_code)
    print(re.text)
    return re.text
